import 'package:core_package/core_package.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/model/loginModel.dart';
import 'package:flutter_app_unionad/request/base_request.dart';

class LoginRequest {
  //发送验证码
  static Future<bool> sendCode({
    int type = 10, //  "type": "10:手机验证码登录, 11:身份验证验证码, 14:用户注册验证码, 15:修改密码验证码, 16:信息变更验证码"
    String? phone,
  }) async {
    try {
      final future = await HttpRequest.postRequest("/api/user/sendCode", params: {
        'phone': phone,
        'type': type,
      });
      bool result = false;
      baseRequestAnalysisData(future, (map) {
        result = true;
      }, (info, code) {
        ShowToastWidget.showToast(msg: info);
        result = false;
      });
      return result;
    } catch (e) {
      ShowToastWidget.showToast(msg: '网络错误,请检查手机网络');

      return false;
    }
  }

  //登录
  static Future<bool> login({
    String? code,
    String? phone,
    String? password,
    int type = 0, //0验证码登录，1密码登录
  }) async {
    try {
      String url = type == 0 ? '/api/user/loginByCode' : '/api/user/loginByPwd';
      Map<String, dynamic> map = {};
      if (phone != null) map['phone'] = phone;
      if (password != null) map['pwd'] = password;
      if (code != null) map['code'] = code;
      final future = await HttpRequest.postRequest(url, params: map);
      bool result = false;
      baseRequestAnalysisData(future, (map) {
        LoginModel model = LoginModel.fromJson(map);

        UserCacheUil.setInt(Configuration.userId, model.userId == null ? 0 : model.userId!.toInt());
        UserCacheUil.setString(Configuration.mobile, phone ?? "");
        UserCacheUil.setString(Configuration.openid, model.uniqId ?? '');
        UserCacheUil.setInt(Configuration.userType, model.userAppRole);

        if (model.devId != null) UserCacheUil.setString(Configuration.deviceId, model.devId ?? '');

        ///保存注册id
        saveJSPushRegister();

        result = true;
      }, (info, code) {
        ShowToastWidget.showToast(msg: info);
        result = false;
      });
      return result;
    } catch (e) {
      ShowToastWidget.showToast(msg: '网络错误,请检查手机网络');
      return false;
    }
  }

  //修改手机号
  static Future<bool> changeMobile({
    String? code,
    String? phone,
  }) async {
    String url = '/api/user/updateUserPhone';
    Map<String, dynamic> map = {};
    if (phone != null) map['phone'] = phone;
    if (code != null) map['code'] = code;
    final future = await HttpRequest.postRequest(url, params: map);
    bool result = false;
    baseRequestAnalysisData(future, (map) {
      UserCacheUil.setString(Configuration.mobile, phone ?? '');
      result = true;
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
      result = false;
    });
    return result;
  }

  //修改密码
  static Future<bool> changePassword({
    String? code,
    String? pwd,
  }) async {
    String url = '/api/user/updateUserPwd2';
    Map<String, dynamic> map = {};
    if (pwd != null) map['pwd'] = pwd;
    if (code != null) map['code'] = code;
    final future = await HttpRequest.postRequest(url, params: map);
    bool result = false;
    baseRequestAnalysisData(future, (map) {
      result = true;
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
      result = false;
    });
    return result;
  }

  //绑定设备  -- 新版本增加手机验证
  static Future<String?> bindingDevice({
    @required String? devId,
    @required String? mobile,
  }) async {
    String url = '/api/user/bindingDevByMobile';
    Map<String, dynamic> map = {};
    if (devId != null) map['devId'] = devId;
    if (mobile != null) map['mobile'] = mobile;
    final future = await HttpRequest.postRequest(url, params: map);
    String? result;
    baseRequestAnalysisData(future, (map) {
      print(map);
      result = map;
      ShowToastWidget.showToast(msg: '绑定成功');
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
    });
    return result;
  }

  /// 绑定设备获取激活手机号
  static Future<String?> bindingDeviceGetMobile({
    @required String? devId,
  }) async {
    String url = '/api/user/getInstallUserMobileByDevId';
    Map<String, dynamic> map = {};
    if (devId != null) map['devId'] = devId;
    final future = await HttpRequest.getRequest(url, params: map);
    String? result;
    baseRequestAnalysisData(future, (map) {
      print(map);
      result = map;
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
    });
    return result;
  }

  //解绑设备
  static Future<bool> unBindingDevice({
    @required String? devId,
  }) async {
    String url = '/api/device/unInitDeviceFormApp';
    print('object');
    Map<String, dynamic> map = {};
    if (devId != null) map['devId'] = devId;

    final future = await HttpRequest.getRequest(url, params: map);
    bool result = false;
    baseRequestAnalysisData(future, (map) {
      UserCacheUil.setString(Configuration.deviceId, '');
      // UserCacheUil.setBool(Configuration.makeAnInstall, false);
      result = true;
      ShowToastWidget.showToast(msg: '解绑成功');
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
      result = false;
    });
    return result;
  }

  //根据微信openid 获取用户信息
  static Future<int> getUserByOpenId(String openId) async {
    String url = '/api/user/getUserByOpenid';
    Map<String, dynamic> map = {};
    if (openId != null) map['openid'] = openId;
    final future = await HttpRequest.getRequest(url, params: map);
    int result = 0;
    baseRequestAnalysisData(future, (map) {
      if (map == null) {
        result = 2;
      } else {
        LoginModel model = LoginModel.fromJson(map);
        if (model.phone == null || model.phone!.stringIsEmpty) {
          result = 2;
        } else {
          UserCacheUil.setInt(Configuration.userType, model.userAppRole);

          UserCacheUil.setInt(Configuration.userId, model.userId == null ? 0 : model.userId!.toInt());
          UserCacheUil.setString(Configuration.mobile, model.phone ?? '');
          UserCacheUil.setString(Configuration.openid, model.uniqId ?? '');
          if (model.devId != null) UserCacheUil.setString(Configuration.deviceId, model.devId ?? '');
          result = 1;
        }
      }
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
      result = 0;
    });
    return result;
  }

//绑定手机号
  static Future<bool> bindPhone(Map<String, dynamic> map, String phone) async {
    final future = await HttpRequest.postRequest('/api/user/bindPhone', params: map);
    bool result = false;
    baseRequestAnalysisData(future, (map) {
      LoginModel model = LoginModel.fromJson(map);
      UserCacheUil.setInt(Configuration.userId, model.userId == null ? 0 : model.userId!.toInt());
      UserCacheUil.setString(Configuration.mobile, phone);
      UserCacheUil.setString(Configuration.openid, model.uniqId ?? '');
      UserCacheUil.setInt(Configuration.userType, model.userAppRole);

      if (model.devId != null) UserCacheUil.setString(Configuration.deviceId, model.devId ?? '');
      result = true;
    }, (info, code) {
      ShowToastWidget.showToast(msg: info);
      result = false;
    });

    return result;
  }

  /// js_push register ID

  static Future<bool> saveJSPushRegister({String? registerID}) async {
    String? registerId = registerID ?? UserCacheUil.getString(Configuration.jsPushRegisterId);
    int? userId = UserCacheUil.getInt(Configuration.userId);
    if (registerId == null || userId == null || userId == 0) {
      ///如果 用户没登录就不需要保存注册id
      return false;
    }
    final future = await HttpRequest.getRequest('/api/user/saveJiguangRegId', params: {
      'regId': registerId,
    });
    bool result = false;
    baseRequestAnalysisData(future, (map) {
      result = true;
    }, (info, code) {
      result = false;
    });
    return result;
  }
}
